package acwing._1_1AlgorithmBasic._3SearchGraph;
/**
 * @Project : AlgorithmLearning
 * @Package : ACWing._1_1AlgorithmBasic._3SearchGraph
 * @File : Q0844.java
 * @Author : WangRuoyu
 * @Date : 2023/4/1 20:44
 */

import java.io.*;
import java.util.LinkedList;
import java.util.Queue;

public class Q0844 {
    static int m;
    static int n;
    static int[][] maze;
    static boolean[][] st;
    static int[][] dis = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        String[] words = br.readLine().split(" ");
        m = Integer.parseInt(words[0]);
        n = Integer.parseInt(words[1]);
        maze = new int[m][n];
        st = new boolean[m][n];

        for (int i = 0; i < m; ++i) {
            words = br.readLine().split(" ");
            for (int j = 0; j < n; ++j) {
                maze[i][j] = Integer.parseInt(words[j]);
            }
        }

        Queue<int[]> q = new LinkedList<>();
        q.add(new int[]{0, 0, 0});
        st[0][0] = true;
        while (!q.isEmpty()) {
            int[] point = q.poll();
            if (point[0] == m - 1 && point[1] == n - 1) {
                System.out.println(point[2]);
                return;
            }
            for (int i = 0; i < 4; ++i) {
                int x = point[0] + dis[i][0];
                int y = point[1] + dis[i][1];
                if (x >= 0 && x < m && y >= 0 && y < n && !st[x][y]&&maze[x][y]!=1) {
                    q.add(new int[]{x, y, point[2] + 1});
                    st[x][y] = true;
                }
            }
        }
        System.out.println(-1);
    }
}

